package com.jhc.config;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jhc.bo.AdminUserDetails;
import com.jhc.bo.UserSaveDetails;
import com.jhc.entity.CmsPermission;
//import com.jhc.entity.CmsTeacher;
import com.jhc.entity.CmsTeacher;
import com.jhc.entity.CmsUser;
import com.jhc.entity.RedisUserInfo;
import com.jhc.service.ICmsTeacherService;
import com.jhc.service.ICmsUserService;
import com.jhc.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zfm
 * @Date: 2019/11/11 22:09
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Slf4j
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private ICmsTeacherService iCmsTeacherService;
    @Autowired
    private ICmsUserService iCmsUserService;
    @Autowired
    private RestfulAccessDeniedHandler restfulAccessDeniedHandler;
    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
    @Autowired
    private RedisService redisService;

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf()
                .disable()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 白名单
                .antMatchers(
                        // swagger api json
                        "/v2/api-docs",
                        // 用来获取支持的动作
                        "/swagger-resources/configuration/ui",
                        // 用来获取api-docs的URI
                        "/swagger-resources",
                        // 安全选项
                        "/swagger-resources/configuration/security",
                        "/swagger-ui.html",
                        "/webjars/**",
                        "/test/**",
                        "/websocket/**",
                        "/images/**"
                )
                .permitAll()
                //用户登录注册
                .antMatchers("/user/login", "/user/register")
                .permitAll()
                // 登陆注册允许匿名访问
                .antMatchers("/teacher/login", "/teacher/register")
                .permitAll()
                // 跨域请求会先进行一次options请求
                .antMatchers(HttpMethod.OPTIONS)
                .permitAll()
//                .anyRequest().permitAll();
//                // 测试时全部运行访问
//                .antMatchers("/**")
//                .permitAll()
                // 除上面外d所有请求全部需要鉴全认证
                .anyRequest()
                .authenticated()
                .and()
                // 自定义 jwt过滤器
                .addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);

        // 禁用缓存
        httpSecurity.headers().cacheControl();

        //添加自定义未授权和未登录结果返回
        httpSecurity.exceptionHandling()
                .accessDeniedHandler(restfulAccessDeniedHandler)
                .authenticationEntryPoint(restAuthenticationEntryPoint);
    }

    @Override
    @Bean
    public UserDetailsService userDetailsService() {
        //获取登录用户信息
        return username -> {
            CmsUser user = iCmsUserService.getOne(new QueryWrapper<CmsUser>().lambda().eq(
                    CmsUser::getNumber, username
            ));
            iCmsUserService.getOne(new QueryWrapper<CmsUser>().lambda().eq(
                    CmsUser::getNumber, username
            ));
            if (user != null) {
                try {
                    RedisUserInfo redisUserInfo = JSON.parseObject(redisService.get(username), RedisUserInfo.class);
                    // 从redis拿权限
                    if (redisUserInfo == null) {
                        redisUserInfo = new RedisUserInfo();
                    }
                    List<CmsPermission> permissionList = redisUserInfo.getPermissionList();
                    if (permissionList == null) {
                        permissionList = new ArrayList<>();
                    }
                    System.out.println(JSON.toJSONString(permissionList));
                    userSaveDetails().setCmsUser(user);
                    return new AdminUserDetails(user, permissionList);
                } catch (Exception e) {
                    throw new UsernameNotFoundException(e.getMessage());
                }
            }
            throw new UsernameNotFoundException("用户名或密码错误");
        };
    }

    @Bean
    public UserSaveDetails userSaveDetails(){
        return new UserSaveDetails();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService())
                .passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() {
        return new JwtAuthenticationTokenFilter();
    }
}
